<template>
	<view class="page">
		<tpf-dock class="dock" :fixed="true" :scrollTop="0" :dockZindex="10">
			<view class="dock-bar-bg"></view>
			<tpf-nav-bar status-bar hasCenter :fixedHeight="navBar.fixedHeight" :navBarStyle="navBar.navBarStyle" :left="navBar.left" :right="navBar.right" @iconTap="navBarIconTap">
				<view class="nav-bar-search-input" slot="center">
					<tpf-search-input :leftIcon="navBar.searchInput.leftIcon" :rightIcon="navBar.searchInput.rightIcon" :searchInputStyle="navBar.searchInput.searchInputStyle" :inputStyle="navBar.searchInput.inputStyle" :placeholder="navBar.searchInput.placeholder"></tpf-search-input>
				</view>
			</tpf-nav-bar>
			<view class="title-tab">
				<view class="title-tab-bar" v-for="(titleTabBar, titleTabBarIndex) of titleTabBarConfig.list" :key="titleTabBarIndex" @tap="titleTabBarTap(titleTabBarIndex, titleTabBar.id)">
					<view class="title-tab-bar-item">
						<text class="title-tab-bar-text">{{titleTabBar.text}}</text>
						<!-- 未被选中时 -->
						<tpf-icon v-if="titleTabBar.icon && currentTitleTabBarIndex !== titleTabBarIndex" class="title-tab-bar-icon" :fontFamily="titleTabBarConfig.fontFamily" :subtitle="titleTabBar.icon.subtitle"></tpf-icon>
						<!-- 被选中时 -->
						<tpf-icon v-if="titleTabBar.selectedIcon && !titleTabBar.isTapped && currentTitleTabBarIndex === titleTabBarIndex" class="title-tab-bar-icon" :fontFamily="titleTabBarConfig.fontFamily" :subtitle="titleTabBar.selectedIcon.subtitle"></tpf-icon>
						<!-- 第一次点击 -->
						<tpf-icon v-if="titleTabBar.tapOnceIcon && currentTitleTabBarIndex === titleTabBarIndex && titleTabBar.isTapped && titleTabBar.tapSwitch" class="title-tab-bar-icon" :fontFamily="titleTabBarConfig.fontFamily" :subtitle="titleTabBar.tapOnceIcon.subtitle"></tpf-icon>
						<!-- 第二次点击 -->
						<tpf-icon v-if="titleTabBar.tapTwiceIcon && currentTitleTabBarIndex === titleTabBarIndex && titleTabBar.isTapped && !titleTabBar.tapSwitch" class="title-tab-bar-icon" :fontFamily="titleTabBarConfig.fontFamily" :subtitle="titleTabBar.tapTwiceIcon.subtitle"></tpf-icon>
					</view>
					
					<view :class="currentTitleTabBarIndex === titleTabBarIndex ? 'title-tab-bar-icon-line' : ''"></view>
				</view>
			</view>
		</tpf-dock>
		
		<tpf-popup type="right" ref="drawer">
			<scroll-view  class="drawer-content" :scroll-y="true" @scroll.stop="stopPropagation">
				<view>
					<view class="service-or-discount-list">
						<uni-collapse>
							<uni-collapse-item title="服务/折扣">
								<view class="collapse-item">
									<uni-grid :column="3" :square="false" :showBorder="false">
										<uni-grid-item v-for="(serviceOrDiscount, serviceOrDiscountIndex) of serviceOrDiscountList" :key="serviceOrDiscountIndex">
											<view class="collapse-item-value">
												<text class="collapse-item-value-text">{{serviceOrDiscount}}</text>
											</view>
										</uni-grid-item>
									</uni-grid>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
					<view class="specification-cate-list">
						<view class="specification-cate" v-for="(specificationCate, specificationCateIndex) of specificationCateList" :key="specificationCateIndex">
							<uni-collapse>
								<uni-collapse-item :title="specificationCate.name">
									<view class="collapse-item">
										<uni-grid :column="3" :square="false" :showBorder="false">
											<uni-grid-item v-for="(specification, specificationIndex) of specificationCate.value" :key="specificationIndex">
												<view class="collapse-item-value">
													<text class="collapse-item-value-text">{{specification}}</text>
												</view>
											</uni-grid-item>
										</uni-grid>
									</view>
								</uni-collapse-item>
							</uni-collapse>
						</view>
					</view>
				</view>
			</scroll-view>
		</tpf-popup>
		
		<view class="product-list-wrap">
			<view class="product-list">
				<view class="product" :class="'product-list-'+productListArrange" v-for="(product, productIndex) of list" :key="productIndex" @tap="goodsDetail(product.id)">
					<tpl-product-one :arrange="productListArrange" :url="product.url" :image="product.goods_thumb" :id="product.id" :title="product.goods_name" :price="Number(product.price)" :priceLabel="product.priceLabel" :productLabelList="product.productLabelList" :commentCount="product.comment_sum || 0" @tapAddCart="addCart"></tpl-product-one>
				</view>
			</view>
			<uni-load-more :status="loadMoreStatus"></uni-load-more>
		</view>
		
		<uni-popup ref="cart" type="bottom">
			<tpl-cart-pop :goodsThumb="goodsThumb" :price="realityPrice" :stock="stock" :stocked="Number(stocked)" :goodsAttrStr="getGoodsAttrSelectedExt.attrsStr" :goodsAttr="goodsAttr" @settlement="settlement" @closePop="closePop"></tpl-cart-pop>
		</uni-popup>
	</view>
</template>

<script>
	import initConfig from '@/mixins/shop/product/product-list.js';
	import data from '@/data/shop/product/product-list.js';
	import BigNumber  from "@/common/js/bignumber.js"
	export default {
		name: 'ProductList',
		mixins: [initConfig],
		data() {
			return {
				scrollTop: 0,
				drawerShowed: false,
				loadMoreStatus : "more",
				
				currentTitleTabBarIndex: -1,
				
				current_goods_id:0,
				
				serviceOrDiscountList: [],
				brandList: [],
				specificationCateList: [],
				listClickCounter : 0,
				filter_click_counter : 0,
				productListArrange:"row",
				
				goodInfo:[],
				stock:1,		//库存
				stocked : 1, 	//选择的库存数
				goodsThumb:"",
				price:"0.00",	//商品本店价
				goodsAttr:[],		// 商品属性
				goodsStorage:[],	//商品管库
				
				requestListUrl:"/Goods/vlist/",
				postData:{
					id:1,
					type:null
				}
			}
		},
		async onLoad(option) {
			const productListData = data.productList();
			const serviceOrDiscountListData = data.serviceOrDiscountList();
			const brandListData = data.brandList();
			const specificationCateListData = data.specificationCateList();
			
			this.list = await productListData;
			this.serviceOrDiscountList = await serviceOrDiscountListData;
			this.brandList = await brandListData;
			this.specificationCateList = await specificationCateListData;
			
			if(option.cateid) this.$set(this.postData,"cateid",option.cateid);
		},
		onPageScroll(e) {
			const scrollTop = e.scrollTop;
			// console.log(e);
			this.scrollTop = scrollTop;
			
		},
		methods: {
			stopPropagation(e) {
				e.stopPropagation();
			},
			navBarIconTap(e) {
				let that = this;
				const action = {
					back() {
						uni.navigateBack({
							delta: 1
						});
					},
					layout() {
						let bowl = that.navBar.right.iconList[0].rowText;
						that.$set(that.navBar.right.iconList[0],"rowText",that.navBar.right.iconList[0].text);
						that.$set(that.navBar.right.iconList[0],"text",bowl); 
						that.listClickCounter++;
						if(that.listClickCounter%2==0){
							console.log("列表排序....");
							that.productListArrange = "row";
						}else{
							console.log("两列排序....");
							that.productListArrange = "col";
						}
					}
				}
				
				if (action[e]) {
					action[e]();
				} else {
					console.log('功能开发中，敬请期待。。。');
				}
				
			},
			
			titleTabBarTap(index, id) {
				let that = this;
				//设置图标
				if (this.currentTitleTabBarIndex !== index) {
					this.filter_click_counter = 1;
					this.currentTitleTabBarIndex = index;
					this.titleTabBarConfig.list.forEach((item, itemIndex) => {
						this.$set(this.titleTabBarConfig.list[itemIndex], 'isTapped', false);
						this.$set(this.titleTabBarConfig.list[itemIndex], 'tapSwitch', false);
					});
					
					
				} else {
					this.filter_click_counter ++ ;
					this.$set(this.titleTabBarConfig.list[index], 'isTapped', true);
					this.$set(this.titleTabBarConfig.list[index], 'tapSwitch', !this.titleTabBarConfig.list[index].tapSwitch);
				}
				let remote_pull_data = false;
				//响应点击事件
				const action = {
					recommend() {
						if(that.filter_click_counter == 1){
							that.initPageData();
							remote_pull_data = true;
							that.postData.type=id;
						}
						//console.log("综合推荐");
					},
					sales() {
						if(that.filter_click_counter == 1){
							that.initPageData();
							remote_pull_data = true;
							that.postData.type=id;
							return true;
						}
						//console.log("销量");
					},
					price() {
						remote_pull_data = true;
						that.initPageData();
						if(that.filter_click_counter % 2 !== 0 ){   //奇数次点数
							that.postData.type=id+"_asc";
						}else{
							that.postData.type=id+"_desc";
						}
						//console.log("价格");
					},
					filter: () => {
						this.$refs['drawer'].open();
					}
				};
				if (action[id]) {
					action[id]();
				} else {
					console.log('功能开发中，敬请期待。。。');
				}
			},
			addCart(goods_id){
				console.log("开始调起产品ID为"+goods_id+"的属性");
				
				this.current_goods_id = goods_id;
			},
			closePop(id){
				id=="cart" && this.$refs.cart.close();
			},
			goodsDetail(goods_id){
				uni.navigateTo({
					url:"product-detail?gods_id="+goods_id
				})
			},
			initPageData(){
				this.loadMoreStatus = "more";
				this.pageData={
					last_page:1,
					total:1
				};
				this.postData={
					current_page:1,
					per_page:10,
					page:1,
					id:1,
					type:null
				};
			},
			
			selectGoodsAttr(attr_id,attr_child_id){
				let arrIds=[];
				this.stock = this.list.stock;
				this.goodsThumb = this.goodInfo.goods_thumb;
				this.goodsAttr.forEach((attr,attrIndex)=>{
					if(attr.id === attr_id){
						attr.attr_list.forEach((child,childIndex)=>{
							child.id==attr_child_id?this.$set(this.goodsAttr[attrIndex].attr_list[childIndex],"checked",true):this.$set(this.goodsAttr[attrIndex].attr_list[childIndex],"checked",false);
						});
					}
					let attr_selected = attr.attr_list.filter(item=>item.checked);
					if(attr_selected.length>0){
						arrIds.push(attr_selected[0].id);
					}
				});
				
				if(arrIds.length == this.goodsAttr.length){
					this.stocked=1;
					this.goodsStorage.forEach((storage,storageIndex)=>{
						if(arrIds.join(",")==storage.goods_attr_ids){
							this.stock = storage.stock;
							if(storage.thumb.length>0) this.goodsThumb = storage.thumb;
						}
					});
				}
			},
			settlement(e){
				try{
					this.goodsAttr.forEach((attr,attrIndex)=>{
						if(attr.attr_list.filter(item=>(item.checked)).length == 0){
							throw new Error(attr.name+"必须");
						}
					});
				}catch(e){
					this.$Helper.tpfToast({title:e.message});
					return false;
				}
				let param = {
					id:this.current_goods_id,
					quantity:this.stocked,
					spec_key:this.getGoodsAttrSelectedExt.ids,
					spec_key_name:this.getGoodsAttrSelectedExt.attrs
				};
				if(this.stock==0 || this.stock<this.stocked){
					this.$Helper.tpfToast({title:"库存不足"});return false;
				}
				// 添加购物车
				if(e=="addToCart"){
					
					this.$refs.cart.close();
				}

				if(e == "goBuy"){
					this.$Helper.tpfJump({url:`/pages/shop/settlement/settlement?id=${param.id}&quantity=${param.quantity}&spec_key=${param.spec_key}&spec_key_name=${param.spec_key_name}`});
				}
			}
		},
		computed:{
			/* *
			*  对选中属性的计算操作
			* arrIds	:选中的属性id列表
			* arrAttrs	:选中的属性值列表
			* select_attr_str	:选中后展示的串
			*/
			getGoodsAttrSelectedExt(){
				let arrIds=[],arrAttrs=[],select_attr_str="请选择";
				this.goodsAttr.forEach((attr,attrIndex)=>{
					let attr_selected = attr.attr_list.filter(item=>item.checked);
					if(attr_selected.length>0){
						arrIds.push(attr_selected[0].id);
						arrAttrs.push(attr_selected[0].attr_value);
					}
				});
				return {
					ids:arrIds.length==0?"":arrIds.join(","),
					attrs:arrAttrs.length==0?"":(arrAttrs.lenght==1?arrAttrs[0]:arrAttrs.join(" ")),
					attrsStr:arrAttrs.length==0 ? 
						"请选择" : ("已选择 "+(arrAttrs.lenght==1?arrAttrs[0]:arrAttrs.join(" ")+"，"+this.stocked+"件"))
					
				}
			},
			/*
			goodsAttrSelectedId(){
				let arr = [];
				this.goodsAttr.forEach((attr,attrIndex)=>{
					let attr_selected = attr.attr_list.filter(item=>item.checked);
					if(attr_selected.length>0) arr.push(attr_selected[0].id);
				});
				return arr.join(",");
			},
			
			goodsAttrSelectedAttr(){
				let arr = [];
				this.goodsAttr.forEach((attr,attrIndex)=>{
					let attr_selected = attr.attr_list.filter(item=>item.checked);
					if(attr_selected.length>0) arr.push(attr_selected[0].attr_value);
				});
				
				return arr.length==0?"":(arr.length==1?arr[0]:arr.join(" "));
			},
			
			goodsAttrStr(){
				let goodsAttr = this.goodsAttr , default_str = "请选择", str="已选择";
				str=this.goodsAttrSelectedAttr.length>0?str+" "+this.goodsAttrSelectedAttr:str;
				return str.length>3?str + "，"+this.stocked+"件":default_str;
			},
			*/
			// 商品实际价格，通过规格计算真实的价格
			realityPrice(){
				let amount = new BigNumber(this.price);
				this.goodsAttr.forEach((attr,attrIndex)=>{
					let attr_selected = attr.attr_list.filter(item=>item.checked);
					if(attr_selected.length>0) amount = amount.plus(attr_selected[0].attr_price);
				});
				return amount.toNumber();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.cart-pop{
		position:relative;
		background-color: $uni-bg-color-white;
		padding:10rpx;
	}
	.cart-pop .base{
		display: flex;
		margin-bottom:16rpx; 
	} 
	.cart-pop .base .thumb-blank{
		width: 30%;position:relative;
	}
	.thumb-blank img{
		max-width: 100%;
		position: absolute;
		left: 0; 
		bottom:0;
		border-width: 1px;;
		border-color: #e8e8e8;
		border-style: solid;
		padding:6rpx;
		box-sizing: border-box;
		background-color: $uni-bg-color-white;
		border-radius:3px;
	}
	.cart-pop .base .cart-info{
		flex: 1;
		margin-left: 10px;
		font-size: $uni-font-size-base;
	}
	.cart-pop .base .cart-info .price{
		font-size: $uni-font-size-base*1.2;
		color: $uni-text-color-red;
	}
	.pop-close-ico{
		position: absolute;
		top: 10rpx;
		right: 10rpx;
	}
	.dock {
		/* #ifndef APP-PLUS-NVUE */
		z-index: 2;
		/* #endif */
	}
	.uni-popup{
		z-index: 11;
	}
	.dock-bar-bg {
		background-color: $uni-bg-color;
		position: absolute;
		top: 0;
		bottom: 0;
		right: 0;
		left: 0;
		
		border-bottom-left-radius: $uni-border-radius-base;
		border-bottom-right-radius: $uni-border-radius-base;
	}
	.nav-bar-search-input {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
	}
	
	.title-tab {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		position: relative;
		/* #endif */
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		
		margin-left: $uni-spacing-col-lg;
		margin-right: $uni-spacing-col-lg;
		margin-bottom: $uni-spacing-row-base;
	}
	.title-tab-bar {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		height: 60rpx;
		justify-content: space-between;
	}
	.title-tab-bar-item {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
	}
	.title-tab-bar-text {
		font-size: $uni-font-size-base;
	}
	.title-tab-bar-icon {
		margin-left: $uni-spacing-col-sm;
	}
	.title-tab-bar-icon-line {
		// margin-top: $uni-spacing-row-sm;
		height: 3px;
		background-color: $uni-border-color;
		background-image: linear-gradient(to right, $uni-bg-color-red, #FFFFFF);
	}
	
	.drawer-content {
		width: 600rpx;
		// height: 600rpx;
		background-color: $uni-bg-color;
	}
	.collapse-item {
		margin: 12px;
	}
	.collapse-item-value {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: center;
		align-items: center;
		
		background-color: $uni-bg-color;
		border-radius: 10000px;
		margin: $uni-spacing-row-sm $uni-spacing-col-base;
		
		height: 60rpx;
		// padding: $uni-spacing-row-sm $uni-spacing-col-base;
	}
	.collapse-item-value-text {
		font-size: $uni-font-size-sm;
	}
	
	.product-list {
		background-color: $uni-bg-color;
		margin-top: $uni-spacing-row-base;
		
		border-radius: $uni-border-radius-base;
		
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-wrap: wrap;
	}
	.product{
		padding: $uni-spacing-row-base $uni-spacing-col-base;
	}
	.product-list-row {
		
	}
	.product-list-col{
		width: 50%;
		box-sizing: border-box;
	}
	.product-list .product-list-col:nth-child(2n){
		padding-left: $uni-spacing-col-base/2;
	}
	.product-list .product-list-col:nth-child(2n+1){
		padding-right: $uni-spacing-col-base/2;
	}
	.attrs{
		font-size: $uni-font-size-base;
		padding-top:16rpx;
	}
	.attrs .attr-tit{
		font-size:$uni-font-size-base*1.1;
		border-left-width:3px;
		border-left-style: solid;
		border-left-color:$uni-text-color-red; 
		padding-left:10rpx;
		line-height: 100%;
		margin-bottom: 16rpx;
	}
	
	.attrs .attr-item .item{
		background-color: $uni-bg-color-grey;
		padding: 6rpx 10rpx;
		margin:0 16rpx 16rpx 0;
		border-radius: 6px;
	}
	.quantity{
		font-size: $uni-font-size-base;
		margin-bottom: 20rpx;
	}
	.btns .btn{
		font-size:$uni-icon-size-sm;
		text-align: center;
		line-height:90rpx;
		color: $uni-text-color-white;
	}
	.add-cart{
		background-color: $uni-btn-bg-color-yellow;
	}
	.go-buy{
		background-color: $uni-btn-bg-color-red;
	}
</style>